from django import forms
from auth_app.models import UserModel
from django.core.handlers.wsgi import WSGIRequest


class BaseForm(forms.Form):
    '''
    该类继承forms.Form
    可接受数据字典作为参数，与Form无区别，作为子表单使用
    可接受WSGIRequest作为参数，获取request基本信息
    '''

    def __init__(self, request=None, *args):
        if isinstance(request, WSGIRequest):  #
            self.user_info = request.USER_INFO
            payload = request.payload
            super(BaseForm, self).__init__(data=payload, *args)
        if isinstance(request, dict):
            super(BaseForm, self).__init__(data=request, *args)

    # 在参数中添加请求用户实例
    def set_operate_user(self, data: dict, field: str):
        '''
        params data:cleaned_data
        params field:model中，用户字段
        '''
        if self.user_info:
            data.setdefault(field, UserModel.objects.get(id=self.user_info['usr_id']))
        return data

    def default_StrField_value(self, data: dict, fields: list, default_value: str = ''):
        # 指定字段类型为字符串且为空时的默认值
        for field in fields:
            if not field in data.keys():
                data.setdefault(field, default_value)
